package org.framework.lazy.cloud.network.heartbeat.protocol.token;

import org.wu.framework.core.utils.ObjectUtils;

import java.util.concurrent.ConcurrentHashMap;

public class AuthenticationTokenContext {


    // key appid value AuthenticationToken
    private static final ConcurrentHashMap<String, AuthenticationToken> m = new ConcurrentHashMap<>();


    /**
     * 设置授权信息
     *
     * @param clientId  客户端ID
     * @param appKey    令牌
     * @param appSecret 迷药
     */
    public static void setAuthenticationToken(String clientId, String appKey, String appSecret) {
        AuthenticationToken authenticationToken = new AuthenticationToken();
        authenticationToken.setUsedByClientId(clientId);
        authenticationToken.setAppKey(appKey);
        authenticationToken.setAppSecret(appSecret);
        AuthenticationTokenContext.setAuthenticationToken(authenticationToken);
    }

    /**
     * 设置授权信息
     *
     * @param authenticationToken 授权信息
     */
    public static void setAuthenticationToken(AuthenticationToken authenticationToken) {
        String key = authenticationToken.getAppKey();
        if (m.containsKey(key)) {
            m.put(key, authenticationToken);
            return;
        }
        m.put(key, authenticationToken);
    }

    /**
     * 获取授权信息
     *
     * @param appKey 令牌key
     */
    public static AuthenticationToken getAuthenticationToken(String appKey) {
        AuthenticationToken p = m.values()
                .stream()
                .filter(authenticationToken -> authenticationToken.getAppKey().equals(appKey))
                .findFirst()
                .orElse(null);
        return p;
    }

    /**
     * 删除授权信息
     *
     * @param appKey 令牌key
     */
    public static void removeAuthenticationToken(String appKey) {
        m.remove(appKey);
    }

    /**
     * 验证令牌
     *
     * @param appKey 令牌key
     */
    public static Boolean verify(String appKey, String appSecret) {
        AuthenticationToken p = m.values()
                .stream()
                .filter(authenticationToken -> authenticationToken.getAppKey().equals(appKey)
                        && authenticationToken.getAppSecret().equals(appSecret)
                )
                .findFirst()
                .orElse(null);
        return ObjectUtils.isNotEmpty(p);
    }


}
